package cn.tedu.fruitshop.filter;

import cn.tedu.fruitshop.security.LoginPrincipal;
import cn.tedu.fruitshop.web.JsonResult;
import cn.tedu.fruitshop.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * 过滤器：jwt授权过滤器
 * 1.判断当前携带的jwt是否有效。
 * 2.解析有效的jwt编码。
 * 3.将认证对象存入Security框架的上下文中
 * 4.放行。
 *
 * @author www
 * @create 2022-11-08 15:09
 */
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    private static final int JWT_MIN_LENGTH = 113;

    @Value("${fruitshop.jwt.secret-key}")
    String secretKey;


    public JwtAuthorizationFilter() {
        log.debug("创建过滤器对象: JwtAuthenrizationFilter");

    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        log.debug("开始执行过滤器的方法...");

        //清空Security框架的上下文。
        SecurityContextHolder.clearContext();

        String jwt = request.getHeader("Authorization");
        log.debug("获取客户端携带的jwt：{}", jwt);
        if (!StringUtils.hasText(jwt) || jwt.length() < JWT_MIN_LENGTH) {
            String message = "jwt为null，或者为空，后者小于最小长度";
            log.debug(message);

            filterChain.doFilter(request, response);
            return;
        }


        // 尝试解析JWT
        log.debug("获取到的JWT被视为有效，准备解析JWT……");
        response.setContentType("application/json; charset=utf-8");
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (SignatureException e) {
            log.debug("解析JWT时出现签名异常：SignatureException");
            String message = "非法访问！！！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);
            String jsonString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            return;
        } catch (MalformedJwtException e) {
            log.debug("解析JWT时出现JWT数据不匹配：MalformedJwtException");
            String message = "非法访问！！！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);
            String jsonString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            return;
        } catch (ExpiredJwtException e) {
            log.debug("jwt数据过期异常：ExpiredJwtException");
            String message = "登录已过期，请重新登录！！！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);

            String jsonString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            return;
        } catch (Throwable e) {
            log.debug("解析JWT时出现Throwable，需要开发人员在JWT过滤器补充对异常的处理");
            String message = "你有异常未处理！！！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);
            String jsonString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            return;
        }
        //从jwt数据中获取id
        Integer id = claims.get("id", Integer.class);
        //从jwt数据中获取用户名
        String username = claims.get("username", String.class);
        //从jwt数据中获取权限字符串。
        String authoritiesJSONString = claims.get("authoritiesJSONString", String.class);
        //解析权限字符串--->转为SimpleGranredAuthorities类型
        List<SimpleGrantedAuthority> simpleGrantedAuthorities =
                JSON.parseArray(authoritiesJSONString, SimpleGrantedAuthority.class);
        log.debug("JWT解码id:{},username:{}", id, username);
        //遍历转换后的权限（SimpleGrantedAuthorities类型）添加到新的集合中（GrantedAuthority）
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        for (SimpleGrantedAuthority simpleGrantedAuthority : simpleGrantedAuthorities) {
            authorities.add(simpleGrantedAuthority);
        }

        LoginPrincipal loginPrincipal = new LoginPrincipal(id, username);

        Authentication authentication = new UsernamePasswordAuthenticationToken(
                loginPrincipal, null, authorities
        );
        log.debug("开始在Security框架上下文中添加authentication对象。");
        SecurityContextHolder.getContext().setAuthentication(authentication);
        log.debug("身份检查完毕，开始放行..");
        filterChain.doFilter(request, response);
    }
}
